﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp4.Models
{
    public static class EnumExtension
    {

        /// <summary>
        /// 通过Description获取枚举
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="description"></param>
        /// <returns></returns>
        public static T GetEnumByDescription<T>(string description) where T : Enum
        {
            foreach (var e in Enum.GetValues(typeof(T)))
            {
                object[] attrs = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attrs == null || attrs.Length <= 0)
                {
                    throw new NullReferenceException();
                }
                var desc = (DescriptionAttribute)attrs[0];
                if (desc.Description == description) return (T)e;
            }

            throw new InvalidEnumArgumentException();
        }

        /// <summary>
        /// 获取枚举Description
        /// </summary>
        /// <param name="em"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum em)
        {
            Type type = em.GetType();
            FieldInfo field = type.GetField(em.ToString());
            if (null == field) return string.Empty;

            object[] attrs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (null == attrs || attrs.Length <= 0) return string.Empty;

            var desc = (DescriptionAttribute)attrs[0];
            return desc.Description;
        }
    }
}
